<template>
  <div>
    <Dialog
      :show="dialogConfig.show"
      :title="dialogConfig.title"
      :buttons="dialogConfig.buttons"
      width="400px"
      :showCancel="false"
      @close="closeDialog"
    >
      <el-form :model="formData" :rules="rules" ref="formDataRef">
     
        <!---input输入-->
        <el-form-item prop="email">
          <el-input
            size="large"
            clearable
            placeholder="请输入邮箱"
            v-model="formData.email"
            maxlength="150"
          >
            <template #prefix>
              <span class="iconfont icon-account"></span>
            </template>
          </el-input>
        </el-form-item>

        <!---1登录密码-->
        <el-form-item prop="password" v-if="showLogin">
          <el-input
            :type="passwordEyeType.passwordEyeOpen ? 'text' : 'password'"
            size="large"
            placeholder="请输入密码"
            v-model="formData.password"
          >
            <template #prefix>
              <span class="iconfont icon-password"></span>
            </template>
            <template #suffix>
              <span
                @click="eyeChange('passwordEyeOpen')"
                :class="[
                  'iconfont',
                  passwordEyeType.passwordEyeOpen
                    ? 'icon-eye'
                    : 'icon-close-eye',
                ]"
              ></span>
            </template>
          </el-input>
        </el-form-item>

        <!--0注册-->
        <div v-if="showRegister">
          <el-form-item prop="code">
            <el-input
              size="large"
              clearable
              placeholder="请输入验证码"
              v-model="formData.code"
              maxlength="20"
            >
              <template #prefix>
                <span class="iconfont icon-email"></span>
              </template>
            </el-input>
            <el-button
              style="margin-left: 10px"
              size="large"
              :disabled="countdown > 0"
              @click="sendVerificationCode"
            >
              {{ countdown > 0 ? countdown + "秒" : "发送验证码" }}
            </el-button>
          </el-form-item>
          <el-form-item prop="userName">
            <el-input
              size="large"
              clearable
              placeholder="请输入用户名"
              v-model="formData.userName"
              maxlength="20"
            >
              <template #prefix>
                <span class="iconfont icon-account"></span>
              </template>
            </el-input>
          </el-form-item>

          <el-form-item prop="registerPassword">
            <el-input
              :type="
                passwordEyeType.registerPasswordEyeOpen ? 'text' : 'password'
              "
              size="large"
              placeholder="请输入密码"
              v-model="formData.registerPassword"
            >
              <template #prefix>
                <span class="iconfont icon-password"></span>
              </template>
              <template #suffix>
                <span
                  @click="eyeChange('registerPasswordEyeOpen')"
                  :class="[
                    'iconfont',
                    passwordEyeType.registerPasswordEyeOpen
                      ? 'icon-eye'
                      : 'icon-close-eye',
                  ]"
                ></span>
              </template>
            </el-input>
          </el-form-item>

          <el-form-item prop="reRegisterPassword">
            <el-input
              :type="
                passwordEyeType.reRegisterPasswordEyeOpen ? 'text' : 'password'
              "
              size="large"
              placeholder="请确认密码"
              v-model="formData.reRegisterPassword"
            >
              <template #prefix>
                <span class="iconfont icon-password"></span>
              </template>
              <template #suffix>
                <span
                  @click="eyeChange('reRegisterPasswordEyeOpen')"
                  :class="[
                    'iconfont',
                    passwordEyeType.reRegisterPasswordEyeOpen
                      ? 'icon-eye'
                      : 'icon-close-eye',
                  ]"
                ></span>
              </template>
            </el-input>
          </el-form-item>
        </div>
        <el-form-item v-if="showLogin">
          <div class="no-account">
            <a href="javascript:void(1)" class="a-link" @click="noHasUser"
              >没有账号？</a
            >
            <a href="javascript:void(0)" class="a-link" @click="forget"
              >忘记密码?</a
            >
          </div>
        </el-form-item>
        <el-form-item v-if="showRegister">
          <a href="javascript:void(1)" class="a-link" @click="hasUser"
            >已有账号</a
          >
        </el-form-item>
        <div v-if="showForget">
          <el-form-item prop="forgetedPassword">
          <el-input
            :type="passwordEyeType.passwordEyeOpen ? 'text' : 'password'"
            size="large"
            placeholder="请输入新密码"
            v-model="formData.forgetedPassword"
          >
            <template #prefix>
              <span class="iconfont icon-password"></span>
            </template>
            <template #suffix>
              <span
                @click="eyeChange('passwordEyeOpen')"
                :class="[
                  'iconfont',
                  passwordEyeType.passwordEyeOpen
                    ? 'icon-eye'
                    : 'icon-close-eye',
                ]"
              ></span>
            </template>
          </el-input>
        </el-form-item>
          <el-form-item prop="code">
            <el-input
              size="large"
              clearable
              placeholder="请输入验证码"
              v-model="formData.code"
              maxlength="20"
            >
              <template #prefix>
                <span class="iconfont icon-email"></span>
              </template>
            </el-input>
            <el-button
              style="margin-left: 10px"
              size="large"
              :disabled="countdown > 0"
              @click="sendVerificationCode"
            >
              {{ countdown > 0 ? countdown + "秒" : "发送验证码" }}
            </el-button>
          </el-form-item>
        </div>
        <el-form-item>
          <el-button type="primary" class="op-btn" @click="doSubmit">
            <span v-if="showRegister">注册</span>
            <span v-if="showLogin">登录</span>
            <span v-if="showForget">提交</span>
          </el-button>
        </el-form-item>
      </el-form>
    </Dialog>
  </div>
</template>

<script setup>
import {
  ref,
  reactive,
  getCurrentInstance,
  nextTick,
  defineProps,
  watch,
  defineEmits,
} from "vue";
import { useRouter, useRoute } from "vue-router";
import { useStore } from "vuex";
import {
  toLogin,
  toRegister,
  getUserInfo,
  getEmail,
  updatePassword,
} from "@/api/user";
import md5 from "js-md5";
const emits = defineEmits();
const props = defineProps({
  showLogin: {
    type: Boolean,
    default: "",
  },
  showRegister: {
    type: Boolean,
    default: "",
  },
});
const showRegister = ref(false);
const showLogin = ref(false);
const showForget = ref(false);
const { proxy } = getCurrentInstance();
const router = useRouter();
const route = useRoute();
const store = useStore();
const formData = ref({});
const formDataRef = ref();
// 倒计时的秒数
const countdown = ref(0);
let code = ref("");
//密码显示隐藏操作
const passwordEyeType = reactive({
  passwordEyeOpen: false,
  registerPasswordEyeOpen: false,
  reRegisterPasswordEyeOpen: false,
});
const eyeChange = (type) => {
  passwordEyeType[type] = !passwordEyeType[type];
};

const dialogConfig = reactive({
  show: false,
  title: "欢迎访问TechTales",
  forget: false,
});
const reset = () => {
  formData.value.email = "";
  formData.value.userName = "";
  formData.value.rePassword = "";
  formData.value.registerPassword = "";
  formData.value.code = "";
  countdown.value = 0;
  proxy.resetForm("formDataRef");
};
watch(
  () => props.showRegister,
  (val) => {
    reset();
    dialogConfig.show = val;
    showRegister.value = val;
    showForget.value = false;
  },
  { immediate: true, deep: true }
);
watch(
  () => props.showLogin,
  (val) => {
    reset();
    dialogConfig.show = val;
    showLogin.value = val;
    showForget.value = false;
  },
  { immediate: true, deep: true }
);

const checkRePassword = (rule, value, callback) => {
  if (value !== formData.value.registerPassword) {
    callback(new Error(rule.message));
  } else {
    callback();
  }
};
const validate_email = (rule, value, callback) => {
  var emailRegExp = /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(\.[a-zA-Z0-9_-])+/;
  var emailRegExp1 = /^([a-zA-Z]|[0-9])(\w|\-)+@[a-zA-Z0-9]+\.([a-zA-Z]{2,4})$/;
  if (
    (!emailRegExp.test(value) && value != "") ||
    (!emailRegExp1.test(value) && value != "")
  ) {
    callback(new Error("请输入有效邮箱格式！"));
  } else {
    callback();
  }
};

//规则限制
const rules = {
  email: [
    { required: true, message: "请输入邮箱" },
    { validator: validate_email },
  ],
  password: [{ required: true, message: "请输入密码" }],
  forgetedPassword: [{ required: true, message: "请输入新密码" }],
  userName: [{ required: true, message: "请输入用户名" }],
  code: [{ required: true, message: "请输入验证码" }],
  registerPassword: [{ required: true, message: "请输入密码" }],
  reRegisterPassword: [
    { required: true, message: "请再次输入密码" },
    { validator: checkRePassword, message: "两次输入的密码不一致" },
  ],
};

// 发送验证码函数
const sendVerificationCode = async () => {
  var emailRegExp = /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(\.[a-zA-Z0-9_-])+/;
  var emailRegExp1 = /^([a-zA-Z]|[0-9])(\w|\-)+@[a-zA-Z0-9]+\.([a-zA-Z]{2,4})$/;
  if (!formData.value.email) {
    proxy.$modal.msgWarning("请输入邮箱");
    return;
  }
  if (
    (!emailRegExp.test(formData.value.email) && formData.value.email != "") ||
    (!emailRegExp1.test(formData.value.email) && formData.value.email != "")
  ) {
    proxy.$modal.msgWarning("请输入正确的邮箱格式");
    return;
  }

  // 如果倒计时已经开始，则直接返回
  if (countdown.value > 0) return;

  // 设置倒计时为60秒
  countdown.value = 60;
  try {
    let res = await getEmail(formData.value.email);
    if(res.code=="1"){
      proxy.$modal.msgSuccess("发送成功");
      code.value = res.data;
    }
   
  } catch (e) {}

  // 启动定时器，每秒减少一秒
  const timer = setInterval(() => {
    countdown.value--;

    // 当倒计时结束时，清除定时器
    if (countdown.value === 0) {
      clearInterval(timer);
    }
  }, 1000);
};
//登录注册提交表单
const doSubmit = () => {
  formDataRef.value.validate(async (valid) => {
    if (!valid) {
      return;
    }

    if (showLogin.value) {
      let result = await toLogin({
        email: formData.value.email,
        password: formData.value.password,
      });
      if (result) {
        localStorage.setItem("token", result.data);
        let res = await getUserInfo();
        store.commit("updataLoginUserInfo", res.data);
        emits("close", showLogin.value);
        proxy.$modal.msgSuccess("登录成功");
        setTimeout(() => {
          history.go(0);
        }, 500);
      }
    }
    if (showRegister.value) {
      if (code.value != formData.value.code) {
        proxy.$modal.msgWarning("验证码错误");
        return;
      }
      try {
        let vv = await toRegister({
          username: formData.value.userName,
          email: formData.value.email,
          password: formData.value.registerPassword,
        });
        if (vv.data == null) {
          reset();
          proxy.$modal.msgSuccess("注册成功");
          showLogin.value = true;
          showRegister.value = false;
        }
      } catch (e) {
        proxy.$modal.error(e);
      }
    }
    if (showForget.value) {
      if (code.value != formData.value.code) {
        proxy.$modal.msgWarning("验证码错误");
        return;
      }
      try {
       let res= updatePassword(formData.value.email,formData.value.forgetedPassword)
        proxy.$modal.msgSuccess("修改成功");
        showForget.value=false
        showLogin.value = true;
        showRegister.value = false;
         
      } catch (e) {}
    }
  });
};

const noHasUser = () => {
  reset();
  showLogin.value = false;
  showRegister.value = true;
  showForget.value = false;
};
const hasUser = () => {
  reset();
  showLogin.value = true;
  showRegister.value = false;
  showForget.value = false;
};
const closeDialog = () => {
  emits("close", showLogin.value);
  dialogConfig.show = false;
};
const forget = () => {
  reset();
  showLogin.value = false;
  showRegister.value = false;
  showForget.value = true;
};
</script>


<style scoped lang="scss">
.send-emali-panel {
  display: flex;
  width: 100%;
  justify-content: space-between;
  .send-mail-btn {
    margin-left: 5px;
  }
}
.rememberme.panel {
  width: 100%;
}
.no-account {
  width: 100%;
  display: flex;
  justify-content: space-between;
}
.op-btn {
  width: 100%;
  box-sizing: border-box;
}

.check-code-panel {
  display: flex;
  .check-code {
    margin-left: 5px;
    cursor: pointer;
  }
}
::v-deep .el-form-item__content {
  flex-wrap: nowrap !important;
}
</style>